const db = uniCloud.database();
const cookie = require('cookie')
randomNum = function(min = 0, max = 10) {
	return Math.round(Math.random() * (max - min)) + min;
}
randomAvatarUrl = () => {
	let a = ['https://tse3-mm.cn.bing.net/th/id/OIP-C.XpnLCXvNjh1PjkvAr-t6nAAAAA?w=210&h=210&c=7&r=0&o=5&pid=1.7',
		'https://tse3-mm.cn.bing.net/th/id/OIP-C.id3YItDsqVwBIiohmCogSgAAAA?w=210&h=210&c=7&r=0&o=5&pid=1.7',
		'https://tse2-mm.cn.bing.net/th/id/OIP-C.FWDygLJAzn-CRnX1xX30zwAAAA?w=210&h=210&c=7&r=0&o=5&pid=1.7',
		`https://tupian.qqw21.com/article/UploadPic/2020-5/202052623103460996.jpg`,
		'https://tupian.qqw21.com/article/UploadPic/2020-9/20209172232571440.jpg',
		'https://p.qqan.com/up/2021-6/2021612102682393.png',
		'https://tupian.qqw21.com/article/UploadPic/2020-7/202071322312980333.jpg',
		'https://p.qqan.com/up/2021-3/2021351114587563.jpg',
		'https://ts1.cn.mm.bing.net/th/id/R-C.e3050cfcfcf639f1730328457fce750f?rik=QlcndX%2bLSXM3NA&riu=http%3a%2f%2fwww.gx8899.com%2fuploads%2fallimg%2f2018030309%2fig53h33pmzi.jpg&ehk=oSWS%2fnSQTZOz0LlTTDJnXgE9eUuQU4trI74taTbzz3A%3d&risl=&pid=ImgRaw&r=0',
		'https://p.qqan.com/up/2021-4/16184547854968092.jpg'
	]
	return a[randomNum(0, 9)]
}

function makeRandom(len) {
	let guid = ''
	for (let i = 1; i <= len; i++) {
		const n = Math.floor(Math.random() * 16.0).toString(16)
		guid += n
	}
	return guid
}


async function getUserFromCookie(this_) {
	let cookieData = null
	if (this_.getClientInfo().source != 'http') {
		cookieData = this_.getParams()[0]
	} else {
		const httpInfo = this_.getHttpInfo()
		cookieData = cookie.parse(httpInfo.headers.cookie || '')
	}
	let {
		userToken
	} = cookieData
	if (!userToken)
		return {
			code: 403,
			msg: 'token不存在或实现'
		}
	const collection = db.collection('users');
	let data = (await collection.where({
		token: userToken
	}).get()).data
	if (data.length == 0)
		return {
			code: 403,
			msg: 'token不存在或实现'
		}
	data = data[0]
	return data
}
module.exports = {
	async getList(parms) {
		let type_id = parms.type_id
		let orderType = parms.orderType
		let name = parms.name
		let year = parms.year
		let count = parseInt(parms.count)
		let page = parseInt(parms.page)
		let vod_id = parseInt(parms.vod_id)
		let searchSame = parms.searchSame
		if (count > 20) count = 20
		const dbCmd = db.command
		const collection = db.collection('videos');
		serch = {
			vod_name: new RegExp(name),
		}
		if (vod_id) {
			serch['vod_id'] = vod_id
			if (searchSame) {
				const $ = db.command.aggregate
				return {
					list: (await db.collection('videos').aggregate()
						.match({
							type_id: parseInt(type_id)
						})
						.addFields({
							dtime: $.abs($.add(['$vod_pubdate', -parseInt(searchSame)])),
						})
						.skip(page * count)
						.limit(count)
						.sort({
							dtime: 1
						})
						.end()).data,
					count: 20
				}
			}
		}
		if (type_id) {
			const classc = db.collection('configs');
			let class_ = (await classc.where({
				name: 'class'
			}).get()).data[0].value
			for (let v of class_) {
				if (v.type_id != type_id) continue
				serch['type_id'] = dbCmd.in(v.type_ids)
				break
			}
		}
		if (year) {
			if (year == 'old') {
				serch['vod_year'] = db.command.lt('2010')
			} else if (year.indexOf('-') != -1) {
				let d = year.split('-')
				let dd = [parseInt(d[0]), parseInt(d[1])]
				let max = Math.max(...dd)
				let min = Math.min(...dd)
				let ddd = []
				while (min <= max) {
					ddd.push(min + '')
					min++
				}
				serch['vod_year'] = db.command.in(ddd)
			} else {
				serch['vod_year'] = db.command.eq(year)
			}
		}
		let orderCmd = `.orderBy('vod_time_add', 'desc')`
		if (orderType) {
			switch (orderType) {
				case '0': //更新时间排序
					break;
				case '1': { //豆瓣评分
					orderCmd = `.orderBy('vod_douban_score', 'desc')`
					break;
				}
				case '2': { //发布时间
					orderCmd = `.orderBy('vod_pubdate', 'desc')`
					break;
				}
				default:
					break;
			}
		}
		// return serch
		let res = {}
		eval(`res=collection.where(serch)${orderCmd}.limit(count).skip(page * count).get()`)
		res = await res
		let count_ = await collection.where(serch).count()
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify({
				list: res.data,
				count: count_.total
			})
		}
	},
	async getSwiper(parms) {
		const collection = db.collection('swiper');
		let type_id = parms.type_id
		let data = (await collection.where({
			type_id
		}).orderBy('vod_index', 'asc').get()).data
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify(data)
		}
	},
	async getClass() {
		const collection = db.collection('configs');
		let data = (await collection.where({
			name: 'class'
		}).get()).data[0].value.sort((a, b) => {
			return a.index - b.index
		})
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify(data)
		}
	},
	async login(parms) {
		let parms_ = parms
		if (this.getClientInfo().source == 'http') {
			let httpInfo = this.getHttpInfo()
			let body = JSON.parse(httpInfo.body)
			parms_ = body
		}
		let {
			user,
			password
		} = parms_
		const collection = db.collection('users');
		let data = (await collection.where({
			user,
			password
		}).get()).data
		if (data.length == 0)
			return {
				mpserverlessComposedResponse: true,
				statusCode: 200,
				body: JSON.stringify({
					code: 100,
					msg: "账户名或密码不正确"
				})
			}
		let token = makeRandom(32)
		let loginIp = this.getClientInfo().clientIP
		await collection.doc(data[0]._id).update({
			token,
			tokentime: new Date().getTime(),
			loginIp: loginIp
		})
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			headers: {
				'content-type': 'application/json',
				'set-cookie': cookie.serialize('userToken', token, {
					maxAge: 60 * 60 * 24 * 7, //一周
					path: "/",
					SameSite: 'none'
				}),
			},
			body: JSON.stringify({
				code: 200
			})
		}
	},
	async register(parms) {
		let parms_ = parms
		if (this.getClientInfo().source == 'http') {
			let httpInfo = this.getHttpInfo()
			let body = JSON.parse(httpInfo.body)
			let parms_ = body
		}
		let {
			user,
			password,
			confirmPassword
		} = parms_
		if (password != confirmPassword || user.length < 6 || password.length < 8)
			return {
				mpserverlessComposedResponse: true,
				statusCode: 200,
				body: JSON.stringify({
					code: 100,
					msg: "请检查注册信息"
				})
			}
		const collection = db.collection('users');
		let data = (await collection.where({
			user
		}).get()).data
		if (data.length > 0)
			return {
				mpserverlessComposedResponse: true,
				statusCode: 200,
				body: JSON.stringify({
					code: 100,
					msg: "账号已存在"
				})
			}
		await collection.add({
			user,
			password: password + '',
			regtime: new Date().getTime(),
			phoneNumber: '',
			avatarUrl: randomAvatarUrl(),
			openid: 0,
			token: '',
			username: "用户" + makeRandom(8)
		})
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify({
				code: 200
			})
		}
	},
	async getUserInfo(e) {
		let userToken = ''
		if (this.getClientInfo().source == 'http') {
			const httpInfo = this.getHttpInfo()
			const cookieData = cookie.parse(httpInfo.headers.cookie || '')
			userToken = cookieData.userToken
		} else {
			userToken = e.userToken
		}
		if (!userToken)
			return {
				code: 403,
				msg: 'token不存在或实现'
			}
		const collection = db.collection('users');
		let data = (await collection.where({
			token: userToken
		}).field({
			'user': true,
			"avatarUrl": true,
			'username': true,
			'token': true
		}).get()).data
		if (data.length == 0)
			return {
				code: 403,
				msg: 'token不存在或实现'
			}
		data = data[0]
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify({
				code: 200,
				data
			})
		}
	},
	async loginOut(e) {
		let userToken = ''
		if (this.getClientInfo().source == 'http') {
			const httpInfo = this.getHttpInfo()
			const cookieData = cookie.parse(httpInfo.headers.cookie || '')
			userToken = cookieData.userToken
		} else {
			userToken = e.userToken
		}
		if (!userToken)
			return {
				code: 403,
				msg: 'token不存在或实现'
			}
		const collection = db.collection('users');
		await collection.where({
			token: userToken
		}).update({
			token: ''
		})
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			headers: {
				'content-type': 'application/json',
				'set-cookie': cookie.serialize('userToken', '', {
					maxAge: 60 * 60 * 24 * 7, //一周
					path: "/",
					SameSite: 'none'
				}),
			},
			body: JSON.stringify({
				code: 200
			})
		}
	},
	async getClassNav() {
		return '[{"type_id":1,"type_pid":0,"type_name":"电视剧"},{"type_id":2,"type_pid":0,"type_name":"电影"},{"type_id":3,"type_pid":1,"type_name":"欧美剧"},{"type_id":4,"type_pid":1,"type_name":"香港剧"},{"type_id":5,"type_pid":1,"type_name":"韩剧"},{"type_id":6,"type_pid":1,"type_name":"日剧"},{"type_id":7,"type_pid":1,"type_name":"马泰剧"},{"type_id":8,"type_pid":0,"type_name":"伦理片"},{"type_id":9,"type_pid":2,"type_name":"动作片"},{"type_id":10,"type_pid":2,"type_name":"爱情片"},{"type_id":11,"type_pid":2,"type_name":"喜剧片"},{"type_id":12,"type_pid":2,"type_name":"科幻片"},{"type_id":13,"type_pid":2,"type_name":"恐怖片"},{"type_id":14,"type_pid":2,"type_name":"剧情片"},{"type_id":15,"type_pid":2,"type_name":"战争片"},{"type_id":16,"type_pid":2,"type_name":"记录片"},{"type_id":17,"type_pid":0,"type_name":"动漫"},{"type_id":20,"type_pid":1,"type_name":"内地剧"},{"type_id":23,"type_pid":2,"type_name":"动画片"},{"type_id":24,"type_pid":17,"type_name":"中国动漫"},{"type_id":25,"type_pid":17,"type_name":"日本动漫"},{"type_id":26,"type_pid":17,"type_name":"欧美动漫"},{"type_id":27,"type_pid":0,"type_name":"综艺"},{"type_id":28,"type_pid":1,"type_name":"台湾剧"},{"type_id":29,"type_pid":0,"type_name":"体育赛事"},{"type_id":30,"type_pid":27,"type_name":"大陆综艺"},{"type_id":31,"type_pid":27,"type_name":"日韩综艺"},{"type_id":32,"type_pid":27,"type_name":"港台综艺"},{"type_id":33,"type_pid":27,"type_name":"欧美综艺"},{"type_id":34,"type_pid":2,"type_name":"灾难片"},{"type_id":35,"type_pid":2,"type_name":"悬疑片"},{"type_id":36,"type_pid":2,"type_name":"犯罪片"},{"type_id":37,"type_pid":2,"type_name":"奇幻片"}]'
		const url = `https://jszyapi.com/api.php/provide/vod/at/json`
		const res = await uniCloud.httpclient.request(
			`${url}?ac=list&pg=1`, {
				method: 'get',
				headers: {
					"User-Agent": `Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36`
				},
				dataType: 'json', // 指定返回值为json格式，自动进行parse
			})
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify(res.data.class)
		}
	},
	async getComment(parms) {
		let {
			vid
		} = parms
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		let data = (await dbJQL.collection('comment,users').where({
			'vod_id': parseInt(vid)
		}).field('user_id{username,avatarUrl},date,com,vod_id').orderBy('date desc').get())

		return data.data;
	},
	async postComment(parms) {
		let {
			vid,
			com
		} = parms
		if (com) {
			if (com.length > 60 || com.length < 5) return {
				code: 304
			}
		}
		let user = await getUserFromCookie(this)
		if (user.code) return user
		const collection = db.collection('comment');
		await collection.add({
			vod_id: parseInt(vid),
			user_id: user._id,
			com: com,
			date: new Date().getTime()
		})
		return {
			code: 200
		}
	},
	async editUserInfo() {
		let user = await getUserFromCookie(this)
		if (user.code) return user
		const httpInfo = this.getHttpInfo()
		let body = JSON.parse(httpInfo.body)
		let parms_ = body
		let {
			username,
			password,
			newPassword
		} = parms_
		let update = {}
		if (password) {
			if (password.length < 8 || newPassword.length < 8)
				return {
					code: 302,
					msg: '密码不合规，请检查后重试'
				}
			if (password == newPassword)
				return {
					code: 302,
					msg: '新密码不可与旧密码相同'
				}
			if (password != user.password)
				return {
					code: 302,
					msg: '原始密码错误，请检查后重试'
				}
			update['password'] = newPassword
		}
		if (username) {
			if (username.length < 2)
				return {
					code: 302,
					msg: '账户不合规，请检查后重试'
				}
			update['username'] = username
		}
		const collection = db.collection('users');
		await collection.doc(user._id).update(update)
		return {
			code: 200
		}
	},
	async upVideoHistry(parms) {
		let user = await getUserFromCookie(this)
		if (user.code) return user
		let parms_ = parms
		if (this.getClientInfo().source == 'http') {
			let httpInfo = this.getHttpInfo()
			let body = JSON.parse(httpInfo.body)
			parms_ = body
		}
		parms_['user_id'] = user._id
		const collection = db.collection('watchHistry');
		let res = (await collection.where({
			user_id: user._id,
			vod_id: parms_.vod_id
		}).get()).data
		if (res.length == 0)
			await collection.add(parms_)
		else
			await collection.doc(res[0]['_id']).update(parms_)
		return {
			code: 200
		}
	},
	async getVideoHistry(e) {
		let user = await getUserFromCookie(this)
		if (user.code) return user
		const collection = db.collection('watchHistry');
		let serch = {
			user_id: user._id
		}
		if (e.vid) serch['vod_id'] = parseInt(e.vid)
		console.log(serch)
		let res = (await collection.where(serch).orderBy('watchTime', 'desc').get()).data
		return {
			code: 200,
			list: res
		}
	},
	async checkPassword(parms) {
		let user = await getUserFromCookie(this)
		if (user.code) return user
		const httpInfo = this.getHttpInfo()
		let body = JSON.parse(httpInfo.body)
		let parms_ = body

		return {
			code: 200,
			match: parms_.password == user.password
		}
	}
}